<template>
  <div>
    <div>
      <!-- 学号搜索框 -->
      <el-input
        placeholder="请输入学号"
        v-model="searchParams.id"
        clearable
        style="width: 120px; margin-right: 20px"
      ></el-input>

      <!-- 姓名搜索框 -->
      <el-input
        placeholder="请输入姓名"
        v-model="searchParams.name"
        clearable
        style="width: 120px; margin-right: 20px"
      ></el-input>

      <!-- 班级搜索框 -->
      <el-select
        placeholder="请选班级"
        v-model="searchParams.stuclass"
        clearable
        style="width: 120px; margin-right: 20px"
      >
      <el-option label="23信安" value="23信安"></el-option>
        <el-option label="23Java" value="23Java"></el-option></el-select>

      <!-- 系别选择框 -->
      <el-select
        v-model="searchParams.dept"
        clearable
        placeholder="请选系别"
        style="width: 120px; margin-right: 20px"
      >
        <el-option label="人工智能" value="人工智能"></el-option>
        <el-option label="体育" value="体育"></el-option>
      </el-select>

      <!-- 搜索按钮 -->
      <el-button type="primary" icon="el-icon-search" @click="handleSearch"
        >搜索</el-button
      >

      <!-- 重置按钮 -->
      <el-button type="info" @click="resetSearch">重置</el-button>
    </div>
    <div>
      <el-button type="primary" @click="openAddDialog">新增学生</el-button>
      <el-button
        type="danger"
        @click="batchDelete"
        :disabled="multipleSelection.length === 0"
      >
        批量删除
      </el-button>
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="学号" width="120">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column
          prop="stuclass"
          label="班级"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="dept"
          label="系别"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="age"
          label="年龄"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="sex"
          label="性别"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="头像" width="200" align="center">
          <template slot-scope="scope">
            <img :src="$baseUrl + scope.row.avatar" width="50px" height="50px" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button @click="handleDelete(scope.row)" type="text" size="small"
              >删除</el-button
            >
            <el-button
              @click="openEditDialog(scope.row)"
              type="text"
              size="small"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增 -->
    <el-dialog
      title="新增学生"
      :visible.sync="showAddDialog"
      width="30%"
      :before-close="handleCloseAddDialog"
    >
      <el-form :model="formAdd" ref="formAdd" label-width="80px">
        <el-form-item label="学号">
          <el-input v-model="formAdd.id" placeholder="学号"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="formAdd.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="formAdd.stuclass" placeholder="班级">
            <el-option label="23信安" value="23信安"></el-option>
            <el-option label="23Java" value="23Java"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系别">
          <el-select v-model="formAdd.dept" placeholder="系别">
            <el-option label="人工智能" value="人工智能"></el-option>
            <el-option label="体育" value="体育"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="formAdd.age" placeholder="年龄"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formAdd.sex" placeholder="性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formAdd.avatar"
              :src="$baseUrl + formAdd.avatar"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseAddDialog">取 消</el-button>
        <el-button type="primary" @click="addStudent">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog
      title="编辑学生"
      :visible.sync="showEditDialog"
      width="30%"
      :before-close="handleCloseEditDialog"
    >
      <el-form :model="formEdit" ref="formEdit" label-width="80px">
        <el-form-item label="学号">
          <el-input
            v-model="formEdit.id"
            placeholder="学号"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="formEdit.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="formEdit.stuclass" placeholder="班级">
            <el-option label="23信安" value="23信安"></el-option>
            <el-option label="23Java" value="23Java"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系别">
          <el-select v-model="formEdit.dept" placeholder="系别">
            <el-option label="人工智能" value="人工智能"></el-option>
            <el-option label="体育" value="体育"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="formEdit.age" placeholder="年龄"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formEdit.sex" placeholder="性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="$baseUrl + '/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formEdit.avatar"
              :src="$baseUrl + formEdit.avatar"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseEditDialog">取 消</el-button>
        <el-button type="primary" @click="updateStudent">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getStudents,
  deleteStudent,
  addStudent as apiAddStudent,
  updateStudent as apiUpdateStudent,
  deleteStudents,
  selectStudents, 
} from "@/api/student";

export default {
  name: "student",
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      showAddDialog: false,
      showEditDialog: false,
      imageUrl: "",
      formAdd: {
        name: "",
        id: "",
        stuclass: "",
        dept: "",
        age: "",
        sex: "",
        avatar: "",
      },
      formEdit: {
        name: "",
        id: "",
        stuclass: "",
        dept: "",
        age: "",
        sex: "",
        avatar: "",
      },
      searchParams: {
        id: "", 
        name: "",    
        stuclass: "", 
        dept: "",     
      },
    };
  },
  created() {
    this.getData();
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.formAdd.avatar = res.data;
      this.formEdit.avatar = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    getData() {
      getStudents().then((res) => {
        this.tableData = res.data;
        console.log(this.tableData);
      });
    },
    handleDelete(row) {
      deleteStudent(row.id).then(() => {
        this.getData();
      });
    },
    openAddDialog() {
      this.showAddDialog = true;
      this.formAdd = {
        name: "",
        id: "",
        stuclass: "",
        dept: "",
        age: "",
        sex: "",
        avatar: "",
      };
    },
    handleCloseAddDialog() {
      this.showAddDialog = false;
    },
    addStudent() {
      apiAddStudent(this.formAdd).then((res) => {
        alert(res.msg);
        this.handleCloseAddDialog();
        this.getData();
      });
    },
    openEditDialog(row) {
      this.showEditDialog = true;
      this.formEdit = { ...row };
    },
    handleCloseEditDialog() {
      this.showEditDialog = false;
    },
    updateStudent() {
      apiUpdateStudent(this.formEdit).then((res) => {
        alert(res.msg);
        this.handleCloseEditDialog();
        this.getData();
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除
    batchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择要删除的学生");
        return;
      }

      const ids = this.multipleSelection.map((student) => student.id);
      this.$confirm("确定要删除选中的学生吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteStudents(ids)
            .then((res) => {
              this.$message.success(res.msg || "删除成功");
              this.getData(); // 重新加载数据
            })
            .catch(() => {
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    handleSearch() {
    // 过滤空值参数
    const params = {};
    for (const key in this.searchParams) {
      if (this.searchParams[key]) {
        params[key] = this.searchParams[key];
      }
    }

    // 调用后端接口
    selectStudents(params)
      .then((res) => {
        this.tableData = res.data;
      })
      .catch(() => {
        this.$message.error("查询失败");
      });
  },

  // 重置搜索条件
  resetSearch() {
    this.searchParams = {
      id: "",
      name: "",
      stuclass: "",
      dept: "",
    };
    this.getData(); // 重新加载全部数据
  },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>